package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass =MemberService.class )
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserDao userDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        // 执行分页查询获取到套餐
        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        List<Member> result = page.getResult();
        for (Member member : result) {
            User user = userDao.findUserByMemberId(member.getId());
            member.setHealthManager(user==null?"无":user.getUsername());
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void addMember(Member member) {
        //添加member表中的数据
        member.setRegTime(new Date());
        memberDao.add(member);
    }

    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override
    public void delete(Integer id) {
        // 查询在订单表中是否有被关联的信息
        List<Order> orders = orderDao.findByMemberId(id);
        if (orders!=null&&orders.size()>0){
            String message = "会员信息被引用!";
            for (Order order : orders) {
                message +="<br/>订单编号:"+order.getId();
            }
            // 会员信息被引用了
            throw new RuntimeException(message);
        }
        memberDao.deleteById(id);
    }

    @Override
    public Member findByPhone(String tel) {
        return memberDao.findByTelephone(tel);
    }


}
